package grpc.server;

import grpc.impl.StudentServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author RJA
 * @version V1.0
 * @Title: grpc.server.demo_1
 * @Description:
 * @date 2019/8/23 17:00
 */
public class GrpcServer {
    private Server server;

    public void start() throws IOException {
        this.server = ServerBuilder.forPort(8899).addService(new StudentServiceImpl()).build().start();
        System.out.println("server started.");

        Runtime.getRuntime().addShutdownHook(new Thread(() ->{
            System.out.println("关闭jvm");
            GrpcServer.this.stop();
        }));
        System.out.println("执行到这里");
    }

    public void stop(){
        if(null != this.server) this.server.shutdown();
    }

    private void awaitTermination() throws InterruptedException {
        if(null != this.server) this.server.awaitTermination(3000, TimeUnit.SECONDS);
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        GrpcServer server = new GrpcServer();
        server.start();
        server.awaitTermination();
    }
}
